package com.iro.blog.web;

import com.iro.blog.Service.BlogsService;
import com.iro.blog.Service.TagService;
import com.iro.blog.Service.TypeService;
import com.iro.blog.handler.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import sun.dc.pr.PRError;

@Controller
public class Indexcontroller {
    @Autowired
    private BlogsService blogsService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;
    @GetMapping("/")
    public String index(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable, Model model){
    model.addAttribute("types",typeService.listTypeTop(6));
    model.addAttribute("tags",tagService.listTagTop(8));
    model.addAttribute("page",blogsService.listBlog(pageable));
    model.addAttribute("recommendBlogs",blogsService.listRecommendBlogTop(1));

        return "index";
    }
    @PostMapping("/search")
    public String search(@PageableDefault(size = 5,sort = {"updateTime"},direction = Sort.Direction.DESC)Pageable pageable, Model model,@RequestParam String query){
        model.addAttribute("page",blogsService.listBlog("%"+query+"%",pageable));
        model.addAttribute("query",query);
        model.addAttribute("recommendBlogs",blogsService.listRecommendBlogTop(1));
        return "search";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable Long id,Model model){
      model.addAttribute("blog",blogsService.getAndConvert(id));
        model.addAttribute("recommendBlogs",blogsService.listRecommendBlogTop(1));
        return "blog";
    }

    @GetMapping("/footer/newblog")
    public String newblogs(Model model){
    model.addAttribute("newblogs",blogsService.listRecommendBlogTop(3));

        return "index :: newblogList";

    }
}
